<?php 
namespace backend\modules\business\methods\cashier;
use backend\modules\business\methods\base\Basemethod;
use common\models\BusMember;
use common\models\BusMemberBeautycard;
use yii\data\Pagination;
use common\models\BusMemberRefund;
use common\models\BusMemberDebt;
/**
 * 退款和缴欠费操作
 * @author      futao
 * @date        2016-3-12
 * @version     2.0
 * @copyright   Copyright 2016 meelier.com
 */
class Refund extends Basemethod
{
	/**
	 * 现金退款
	 * @date: 2016-3-12 
	 * @author: futao
	 */
	public function cashRefund()
	{
		if(!\Yii::$app->request->isPost){
			$this->setlayout('/alert');
			$this->disableDebugtool();
			$memberId = \Yii::$app->session->get('member_id');
			if($memberId < 1){
				$this->errorjs('会员ID错误！');
			}
			return $this->render('cashrefund',['member_id'=>$memberId]);
		}
		$memberId = intval($this->postParam('member_id',0));
		$amount = $this->postParam('amount',0);
		if($memberId < 1){
			$this->errorjs('会员ID错误！');
		}
		$where = $this->where;
		$where[] = 'member_id = :member_id';
		$bind[':member_id'] = $memberId;
		$whereStr = implode(' and ', $where);
		$memberInfo = BusMember::find()
		->where($whereStr,$bind)->one();
		if(!$memberInfo){
			$this->errorjs('会员ID错误！');
		}
		$transaction = \Yii::$app->db->beginTransaction();
		try {
			$memberModel = new BusMember();
			$data['consume_amount'] = $amount;
			$data['consume_name'] = '退款';
			$data['consume_type'] = '退款';
			$data['shop_id'] = $this->userInfo->shop_id;
			$data['boss_id'] = $this->userInfo->boss_uid;
			$memberModel->addMemberconsume($memberId,$data);
			$refundModel = new BusMemberRefund();
			$refundModel->member_id = $memberId;
			$refundModel->refund_type = '退现金';
			$refundModel->refund_time = date('Y-m-d H:i:s');
			$refundModel->refund_amount = $amount;
			$refundModel->refund_reason = '无';
			$refundModel->shop_id = $this->userInfo->shop_id;
			$refundModel->save(false);
			$transaction->commit();
			$this->errorjs('退款成功！',1);
		}catch (\Exception $e){
			$transaction->rollBack();
			$this->errorjs('退款失败!');
		}
	}
	/**
	 * 退疗程卡
	 * @date: 2016-3-12 
	 * @author: futao
	 */
	public function healthCardrefund()
	{
		if(!\Yii::$app->request->isPost){
			$this->setlayout('/alert');
			$this->disableDebugtool();
			$title = $this->getParam('title','');
			$memberId = \Yii::$app->session->get('member_id');
			if($memberId < 1){
				$this->errorjs('会员ID错误！');
			}
			$memberInfo = BusMember::find()
			->where('shop_id = :shop_id and member_id = :member_id',[':shop_id'=>$this->userInfo->shop_id,':member_id'=>$memberId])
			->one();
			if(!$memberInfo){
				$this->errorjs('会员ID错误！');
			}
			$where = $this->where;
			$where[] = 'member_id = :member_id';
			$bind[':member_id'] = $memberId;
			$where[] = 'card_name like :title';
			$bind[':title'] = '%'.$title.'%';
			$where[] = 'remain_times > 0';
			$whereStr = implode(' and ', $where);
			$query = BusMemberBeautycard::find()
			->where($whereStr,$bind);
			$queryCount = clone $query;
			$page = new Pagination(['totalCount' => $queryCount->count(),'pageSize' => $this->pageNavLimit]);
			$list = $query
			->offset($page->offset)
			->limit($page->limit)
			->orderBy('card_id desc')
			->asArray()
			->all();
			return $this->render('healthcardrefund',['list'=>$list,'page'=>$page]);
		}
		$cardId = $this->postParam('card_id',0);
		$amount = $this->postParam('amount',0);
		if($cardId < 1 || $amount < 0){
			$this->setError('请求参数错误！');
		}
		$memberId = \Yii::$app->session->get('member_id');
		$memberInfo = BusMember::find()
		->where('shop_id = :shop_id and member_id = :member_id',[':shop_id'=>$this->userInfo->shop_id,':member_id'=>$memberId])
		->one();
		if(!$memberInfo){
			$this->errorjs('会员信息错误！');
		}
		$cardModel = BusMemberBeautycard::find()
		->where('card_id = :id and shop_id = :shop_id',[':id'=>$cardId,':shop_id'=>$this->userInfo->shop_id])
		->one();
		if(!$cardModel){
			$this->errorjs('疗程卡信息错误！');
		}
		$refundInfo = $cardModel->card_name."(".$cardModel->remain_times."/".$cardModel->total_times.")";
		$transaction = \Yii::$app->db->beginTransaction();
		try {
			/* $cardModel->remain_times = 0;
			$cardModel->save(false); */
			$memberModel = new BusMember();
			$data['consume_amount'] = $amount;
			$data['consume_name'] = '退款';
			$data['consume_type'] = '退款';
			$data['shop_id'] = $this->userInfo->shop_id;
			$data['boss_id'] = $this->userInfo->boss_uid;
			$memberModel->addMemberconsume($memberId,$data);
			$refundModel = new BusMemberRefund();
			$refundModel->member_id = $memberId;
			$refundModel->refund_type = '退疗程卡';
			$refundModel->refund_time = date('Y-m-d H:i:s');
			$refundModel->refund_amount = $amount;
			$refundModel->refund_reason = '无';
			$refundModel->shop_id = $this->userInfo->shop_id;
			$refundModel->refund_healcard = $refundInfo;
			$refundModel->save(false);
			$cardModel->delete();
			$transaction->commit();
			$this->formatData();
		}catch (\Exception $e){
			$this->setError('退款失败！');
			$transaction->rollBack();
		}
	}
	/**
	 * 退储值卡
	 * @date: 2016-3-12 
	 * @author: futao
	 */
	public function balanceCardrefund()
	{
		if(!\Yii::$app->request->isPost){
			$this->setlayout('/alert');
			$this->disableDebugtool();
			$memberId = \Yii::$app->session->get('member_id');
			if($memberId < 1){
				$this->errorjs('会员ID错误！');
			}
			$memberInfo = BusMember::find()
			->where('shop_id = :shop_id and member_id = :member_id',[':shop_id'=>$this->userInfo->shop_id,':member_id'=>$memberId])
			->one();
			if(!$memberInfo){
				$this->errorjs('会员ID错误！');
			}
			return $this->render('balancecardrefund',['member_info'=>$memberInfo]);
		}
		$memberId = \Yii::$app->session->get('member_id');
		$memberInfo = BusMember::find()
		->where('shop_id = :shop_id and member_id = :member_id',[':shop_id'=>$this->userInfo->shop_id,':member_id'=>$memberId])
		->one();
		if(!$memberInfo){
			$this->errorjs('会员ID错误！');
		}
		$balance = $this->postParam('balance',0);
		$giveBalance = $this->postParam('give_balance',0);
		$cash = $this->postParam('cash',0);
		$memberModel = new BusMember();
		$memberBalance = $memberInfo->member_balance;
		$memberGivebalance = $memberInfo->member_give_balance;
		$data['member_balance'] = $memberBalance - $balance;
		$data['member_give_balance'] = $memberGivebalance - $giveBalance;
		$transaction = \Yii::$app->db->beginTransaction();
		try {
			$memberModel->updateMemberinfo($memberId, $data);
			unset($data);
			$data['consume_amount'] = $cash;
			$data['consume_name'] = '退款';
			$data['consume_type'] = '退款';
			$data['shop_id'] = $this->userInfo->shop_id;
			$data['boss_id'] = $this->userInfo->boss_uid;
			$memberModel->addMemberconsume($memberId,$data);
			$refundModel = new BusMemberRefund();
			$refundModel->member_id = $memberId;
			$refundModel->refund_type = '退储值卡';
			$refundModel->refund_time = date('Y-m-d H:i:s');
			$refundModel->refund_amount = $cash;
			$refundModel->refund_reason = '无';
			$refundModel->shop_id = $this->userInfo->shop_id;
			$refundModel->refund_balance = $balance;
			$refundModel->refund_givebalance = $giveBalance;
			$refundModel->save(false);
			$transaction->commit();
			$this->errorjs('退款成功!',1);
		}catch (\Exception $e){
			$transaction->rollBack();
			//echo $e->getMessage().$e->getLine();
			$this->errorjs('退款失败!'.$e->getMessage().$e->getLine());
		}	
	}
	/**
	 * 欠款列表
	 * @date: 2016-3-15 
	 * @author: futao
	 */
	public function arrearsList()
	{
		$this->setlayout('/alert');
		$this->disableDebugtool();
		$this->pageNavLimit = 3;
		$name = $this->getParam('name','');
		if($name!=''){
			$where[] = 'member.member_name like :name';
			$bind[':name'] = '%'.$name.'%';
		}
		$where[] = 'bus_member_debt.shop_id = :shop_id';
		$bind[':shop_id'] = $this->userInfo->shop_id;
		$where[] = 'bus_member_debt.debt_state = 0';
		$whereStr = implode(' and ', $where);
		$query = BusMemberDebt::find()
		->select([
			'bus_member_debt.*',
			'member.member_name'
		])
		->leftJoin('bus_member as member','member.member_id = bus_member_debt.member_id')
		->where($whereStr,$bind);
		$queryCount = clone $query;
		$page = new Pagination(['totalCount' => $queryCount->count(),'pageSize' => $this->pageNavLimit]);
		$list = $query
		->offset($page->offset)
		->limit($page->limit)
		->orderBy('debt_id desc')
		->asArray()
		->all();
		return $this->render('arrearslist',['page'=>$page,'list'=>$list]);
	}
	/**
	 * 缴欠款
	 * @date: 2016-3-15 
	 * @author: futao
	 */
	public function arrears()
	{
		if(!\Yii::$app->request->isPost){
			$this->setlayout('/alert');
			$this->disableDebugtool();
			$id = intval($this->getParam('id',0));
			if($id<1){
				$this->errorjs('会员信息错误！');
			}
			$info = BusMemberDebt::find()
			->where("debt_id = {$id} and shop_id = :shop_id",[':shop_id'=>$this->userInfo->shop_id])
			->one();
			if(!$info){
				$this->errorjs('请求参数错误！');
			}
			return $this->render('arrears',['id'=>$id,'info'=>$info]);
		}
		$id = intval($this->postParam('id',0));
		$cashPay = $this->postParam('cash_pay',0);
		$unionPay = $this->postParam('union_pay',0);
		if($id<1){
			$this->errorjs('会员信息错误！');
		}
		$info = BusMemberDebt::find()
		->where("debt_id = {$id} and shop_id = :shop_id",[':shop_id'=>$this->userInfo->shop_id])
		->one();
		if(!$info){
			$this->errorjs('请求参数错误！');
		}
		$amount = $cashPay+$unionPay;
		if($amount > $info->debt_count){
			$this->errorjs('输入金额不能大于欠款金额');
		}
		$transaction = \Yii::$app->db->beginTransaction();
		try {
			if($amount == $info->debt_count){
				$info->already_paid = $info->total_count;
				$info->debt_count = 0;
				$info->debt_state = 1;
				$info->save(false);
			}else if($amount < $info->debt_count){
				$info->already_paid = $info->already_paid + $amount;
				$info->debt_count = $info->debt_count - $amount;
				$info->save(false);
			}
			$memberModel = new BusMember();
			$data['consume_amount'] = $amount;
			$data['consume_name'] = $info->debt_name;
			$data['consume_type'] = '缴欠款';
			$data['cash_pay'] = $cashPay ? $cashPay : 0;
			$data['unionpay'] = $unionPay ? $unionPay : 0;
			$data['balance_pay'] = 0;
			$data['give_pay'] = 0;
			$data['debt_count'] = 0;
			$data['boss_id'] = $this->userInfo->boss_uid;
			$data['shop_id'] = $this->userInfo->shop_id;
			$memberModel->addMemberconsume($info->member_id , $data);
			unset($data);
			$memberInfo = BusMember::findOne($info->member_id);
			$data['member_balance'] = $memberInfo->member_balance;
			$data['member_give_balance'] = $memberInfo->member_give_balance;
			$data['member_debt'] = $memberInfo->member_debt - $amount;
			$memberModel->updateMemberinfo($info->member_id,$data);
			$logdata['member_debt'] = $data['member_debt'];
			$logdata['type'] = '欠款';
			$logdata['account_type'] = 2;
			$logdata['account_money'] = $amount;
			$memberModel->memberBalancelog($info->member_id, $logdata);
			$transaction->commit();
			$this->errorjs('缴费成功！',1);
		}catch (\Exception $e){
			$transaction->rollBack();
			$this->errorjs('缴费失败!');
		}
	}
}
?>